package com.fuchen.academic.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.fuchen.academic.constants.Const;

public class LoginedFilter extends OncePerRequestFilter {

	private static final String[] NOT_ALLOW_URLS = {
		"/login","/signup"
	};
	
	@Override
	protected void doFilterInternal(HttpServletRequest req,
			HttpServletResponse resp, FilterChain chain)
			throws ServletException, IOException {

		String uri = req.getRequestURI();
		
		Object users = req.getSession().getAttribute(Const.CURRENT_USER);
		
		if(null != users){
			
			boolean doFilter = false;
			
			for(String url : NOT_ALLOW_URLS){
				if(uri.endsWith(url)){
					doFilter = true;
					break;
				}
			}
			if(doFilter){
				resp.sendRedirect(req.getServletContext().getContextPath()+"/index");
			}else{
				chain.doFilter(req, resp);
			}
		}else{
			chain.doFilter(req, resp);
		}
	}

}
